package oa.system

import grails.gorm.DetachedCriteria
import groovy.transform.ToString

import org.codehaus.groovy.util.HashCodeHelper
import grails.compiler.GrailsCompileStatic

@GrailsCompileStatic
@ToString(cache=true, includeNames=true, includePackage=false)
class OpAuth implements Serializable {

	private static final long serialVersionUID = 1

	Op op
	Auth auth

	@Override
	boolean equals(other) {
		if (other instanceof OpAuth) {
			other.opId == op?.id && other.authId == auth?.id
		}
	}

    @Override
	int hashCode() {
	    int hashCode = HashCodeHelper.initHash()
        if (op) {
            hashCode = HashCodeHelper.updateHash(hashCode, op.id)
		}
		if (auth) {
		    hashCode = HashCodeHelper.updateHash(hashCode, auth.id)
		}
		hashCode
	}

	static OpAuth get(long opId, long authId) {
		criteriaFor(opId, authId).get()
	}

	static boolean exists(long opId, long authId) {
		criteriaFor(opId, authId).count()
	}

	private static DetachedCriteria criteriaFor(long opId, long authId) {
		OpAuth.where {
			op == Op.load(opId) &&
			auth == Auth.load(authId)
		}
	}

	static OpAuth create(Op op, Auth auth, boolean flush = false) {
		def instance = new OpAuth(op: op, auth: auth)
		instance.save(flush: flush)
		instance
	}

	static boolean remove(Op u, Auth r) {
		if (u != null && r != null) {
			OpAuth.where { op == u && auth == r }.deleteAll()
		}
	}

	static int removeAll(Op u) {
		u == null ? 0 : OpAuth.where { op == u }.deleteAll() as int
	}

	static int removeAll(Auth r) {
		r == null ? 0 : OpAuth.where { auth == r }.deleteAll() as int
	}

	static constraints = {
	    op nullable: false
		auth nullable: false, validator: { Auth r, OpAuth ur ->
			if (ur.op?.id) {
				if (OpAuth.exists(ur.op.id, r.id)) {
				    return ['userRole.exists']
				}
			}
		}
	}

	static mapping = {
		id composite: ['op', 'auth']
		version false
	}
}
